import $http from '@/api/request.js'
// 按需引入消息提示组件，因为在vuex仓库中，访问不到this.$message
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    // 用户订单数据
    userOrders: []
  }
}

const state = getDefaultState()

const mutations = {
  // 通过用户名获取订单信息
  async getUserOrder(state, username) {
    const res = await $http({ url: `/api/public/v1/admin/getuserorders?username=${username}`, method: 'get' })
    if (res.meta.status !== 200 && res.meta.status !== 400) {
      Message.error('获取用户订单失败')
      this.commit('order/clearUserOrders')
      return
    }
    if (res.meta.status === 400) {
      Message.error(res.meta.msg)
      this.commit('order/clearUserOrders')
      return
    }
    if (res.message.userOrders.length === 0) {
      Message.info('该用户暂无订单信息')
      this.commit('order/clearUserOrders')
      return
    }
    state.userOrders = res.message.userOrders
    this.commit('order/orderState')
  },
  // 计算出订单的状态，向订单信息中添加 order_state 字段
  orderState(state) {
    state.userOrders.forEach(item => {
      if (item.is_close) return (item.order_state = '交易关闭')
      if (item.is_return) return (item.order_state = '待退款')
      if (item.is_receive) return (item.order_state = '交易完成')
      if (!item.is_pay) return (item.order_state = '待付款')
      if (item.is_pay && !item.is_deliver) return (item.order_state = '待发货')
      if (item.is_pay && item.is_deliver && !item.is_receive) return (item.order_state = '待收货')
    })
  },
  // 清除用户订单信息
  clearUserOrders(state) {
    state.userOrders = []
  }
}

const actions = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
